<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 项目概览 -->
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>项目概览</span>
          </div>
          <el-row :gutter="20" v-loading="loading">
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ stats.totalProjects }}</div>
                <div class="stat-label">总项目数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ stats.activeProjects }}</div>
                <div class="stat-label">进行中</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ stats.completedProjects }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ stats.totalTasks }}</div>
                <div class="stat-label">总任务数</div>
              </div>
            </el-col>
          </el-row>
          
          <el-row :gutter="20" style="margin-top: 20px;" v-loading="loading">
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ stats.activeTasks }}</div>
                <div class="stat-label">进行中任务</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ stats.completedTasks }}</div>
                <div class="stat-label">已完成任务</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ stats.taskCompletionRate }}%</div>
                <div class="stat-label">任务完成率</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-number">{{ stats.avgProgress }}%</div>
                <div class="stat-label">平均进度</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 我的项目 -->
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>我的项目</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="goToProjects">查看全部</el-button>
          </div>
          <div v-if="myProjects.length === 0" class="empty-state">
            <el-empty description="暂无项目"></el-empty>
          </div>
          <div v-else>
            <div v-for="project in myProjects" :key="project.projectId" class="project-item">
              <div class="project-info">
                <div class="project-name">{{ project.projectName }}</div>
                <div class="project-code">{{ project.projectCode }}</div>
              </div>
              <div class="project-progress">
                <el-progress :percentage="Number(project.progress) || 0" :stroke-width="6"></el-progress>
              </div>
              <div class="project-status">
                <el-tag :type="getStatusType(project.status)">{{ getStatusText(project.status) }}</el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 我的任务 -->
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>我的任务</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="goToTasks">查看全部</el-button>
          </div>
          <div v-if="myTasks.length === 0" class="empty-state">
            <el-empty description="暂无任务"></el-empty>
          </div>
          <div v-else>
            <div v-for="task in myTasks" :key="task.taskId" class="task-item">
              <div class="task-info">
                <div class="task-name">{{ task.taskName }}</div>
                <div class="task-project">{{ task.projectName }}</div>
              </div>
              <div class="task-progress">
                <el-progress :percentage="Number(task.progress) || 0" :stroke-width="6"></el-progress>
              </div>
              <div class="task-status">
                <el-tag :type="getTaskStatusType(task.status)">{{ getTaskStatusText(task.status) }}</el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 项目进度统计 -->
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>项目进度统计</span>
          </div>
          <div id="projectProgressChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getDashboardStats, getMyProjects, getMyTasks } from "@/api/pm/dashboard";
import * as echarts from 'echarts';

export default {
  name: "PmDashboard",
  data() {
    return {
      stats: {
        totalProjects: 0,
        activeProjects: 0,
        completedProjects: 0,
        totalTasks: 0,
        activeTasks: 0,
        completedTasks: 0,
        taskCompletionRate: 0,
        avgProgress: 0
      },
      myProjects: [],
      myTasks: [],
      loading: false,
      myChart: null
    };
  },
  created() {
    this.loadData();
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
    
    // 监听窗口大小变化
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 清理图表和事件监听
    if (this.myChart) {
      this.myChart.dispose();
      this.myChart = null;
    }
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    /** 加载数据 */
    loadData() {
      this.loading = true;
      this.loadStats();
      this.loadMyProjects();
      this.loadMyTasks();
    },
    /** 加载统计数据 */
    loadStats() {
      getDashboardStats().then(response => {
        if (response.code === 200) {
          this.stats = { ...this.stats, ...response.data };
          this.$nextTick(() => {
            this.updateChart();
          });
        }
      }).catch(error => {
        console.error('获取统计数据失败:', error);
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 加载我的项目 */
    loadMyProjects() {
      getMyProjects().then(response => {
        if (response.code === 200) {
          this.myProjects = response.data.slice(0, 5); // 只显示前5个
        }
      }).catch(error => {
        console.error('获取项目列表失败:', error);
      });
    },
    /** 加载我的任务 */
    loadMyTasks() {
      getMyTasks().then(response => {
        if (response.code === 200) {
          this.myTasks = response.data.slice(0, 5); // 只显示前5个
        }
      }).catch(error => {
        console.error('获取任务列表失败:', error);
      });
    },
    /** 初始化图表 */
    initChart() {
      const chartDom = document.getElementById('projectProgressChart');
      if (!chartDom) return;
      
      this.myChart = echarts.init(chartDom);
      this.updateChart();
    },
    /** 更新图表 */
    updateChart() {
      if (!this.myChart) return;
      
      const option = {
        title: {
          text: '项目状态分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['规划中', '进行中', '已完成', '已暂停', '已取消']
        },
        series: [
          {
            name: '项目状态',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '60%'],
            data: [
              { value: this.stats.projectStatusDistribution?.planning || 0, name: '规划中', itemStyle: { color: '#409EFF' } },
              { value: this.stats.activeProjects || 0, name: '进行中', itemStyle: { color: '#67C23A' } },
              { value: this.stats.completedProjects || 0, name: '已完成', itemStyle: { color: '#909399' } },
              { value: this.stats.projectStatusDistribution?.paused || 0, name: '已暂停', itemStyle: { color: '#E6A23C' } },
              { value: this.stats.projectStatusDistribution?.cancelled || 0, name: '已取消', itemStyle: { color: '#F56C6C' } }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              show: true,
              formatter: '{b}: {c}'
            }
          }
        ]
      };
      
      this.myChart.setOption(option);
    },
    /** 获取项目状态类型 */
    getStatusType(status) {
      if (!status) return 'info';
      const statusMap = {
        'planning': 'info',
        'active': 'success',
        'completed': 'success',
        'paused': 'warning',
        'cancelled': 'danger'
      };
      return statusMap[status] || 'info';
    },
    /** 获取项目状态文本 */
    getStatusText(status) {
      const statusMap = {
        'planning': '规划中',
        'active': '进行中',
        'completed': '已完成',
        'paused': '已暂停',
        'cancelled': '已取消'
      };
      return statusMap[status] || status;
    },
    /** 获取任务状态类型 */
    getTaskStatusType(status) {
      if (!status) return 'info';
      const statusMap = {
        'todo': 'info',
        'in_progress': 'primary',
        'completed': 'success',
        'paused': 'warning',
        'cancelled': 'danger'
      };
      return statusMap[status] || 'info';
    },
    /** 获取任务状态文本 */
    getTaskStatusText(status) {
      const statusMap = {
        'todo': '待开始',
        'in_progress': '进行中',
        'completed': '已完成',
        'paused': '已暂停',
        'cancelled': '已取消'
      };
      return statusMap[status] || status;
    },
    /** 跳转到项目管理 */
    goToProjects() {
      this.$router.push('/pm/project');
    },
    /** 跳转到任务管理 */
    goToTasks() {
      this.$router.push('/pm/task');
    },
    /** 处理窗口大小变化 */
    handleResize() {
      if (this.myChart) {
        this.myChart.resize();
      }
    }
  }
};
</script>

<style scoped>
.stat-card {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.project-item, .task-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.project-item:last-child, .task-item:last-child {
  border-bottom: none;
}

.project-info, .task-info {
  flex: 1;
}

.project-name, .task-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.project-code, .task-project {
  font-size: 12px;
  color: #999;
}

.project-progress, .task-progress {
  flex: 1;
  margin: 0 16px;
}

.project-status, .task-status {
  width: 80px;
  text-align: right;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}
</style>
